package com.dms.modules.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.exception.BusinessException;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.product.dto.ProductSpecDTO;
import com.dms.modules.product.entity.ProductSpecTemplate;
import com.dms.modules.product.entity.GlobalSpecTemplate;
import com.dms.modules.product.service.ProductSpecTemplateService;
import com.dms.modules.product.service.GlobalSpecTemplateService;
import com.dms.modules.merchant.entity.Merchant;
import com.dms.modules.merchant.service.MerchantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/api/v1/product-specs")
@Api(tags = "商品规格接口")
@Validated
public class ProductSpecController extends BaseProductController {

    @Autowired
    private ProductSpecTemplateService specTemplateService;

    @Autowired
    private GlobalSpecTemplateService globalSpecService;

    @Autowired
    private MerchantService merchantService;

    @Data
    public static class SpecTemplatesDTO {
        private List<GlobalSpecTemplate> globalSpecs;
        private List<ProductSpecTemplate> categorySpecs;
    }

    /**
     * 检查当前用户是否拥有指定角色
     */
    private boolean hasRole(String role) {
        return SecurityContextHolder.getContext().getAuthentication()
                .getAuthorities().contains(new SimpleGrantedAuthority("ROLE_" + role));
    }

    @GetMapping("/merchant/templates")
    @ApiOperation("获取商家的规格模板列表")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<List<ProductSpecTemplate>> getMerchantTemplates(
            @RequestParam(required = false) Long categoryId) {
        try {
            // 获取当前商家ID
            Long userId = SecurityUtils.getCurrentUserId();
            Merchant merchant = merchantService.getOne(new LambdaQueryWrapper<Merchant>()
                    .eq(Merchant::getUserId, userId));
            if (merchant == null) {
                throw new BusinessException("未获取到商家信息");
            }

            // 获取规格模板列表
            List<ProductSpecTemplate> templates = specTemplateService.listByMerchantId(merchant.getId(), categoryId);
            return ApiResponse.success(templates);
        } catch (BusinessException e) {
            log.error("获取商家规格模板失败: error={}", e.getMessage());
            return ApiResponse.error(e);
        } catch (Exception e) {
            log.error("获取商家规格模板失败", e);
            return ApiResponse.error("获取商家规格模板失败");
        }
    }

    @GetMapping("/global/templates")
    @ApiOperation("获取全局规格模板列表")
    @PreAuthorize("hasAnyRole('MERCHANT','ADMIN')")
    public ApiResponse<List<GlobalSpecTemplate>> getGlobalTemplates() {
        try {
            List<GlobalSpecTemplate> templates = globalSpecService.getEnabledSpecs();
            return ApiResponse.success(templates);
        } catch (BusinessException e) {
            log.error("获取全局规格模板失败: error={}", e.getMessage());
            return ApiResponse.error(e);
        } catch (Exception e) {
            log.error("获取全局规格模板失败", e);
            return ApiResponse.error("获取全局规格模板失败");
        }
    }


    @GetMapping("/merchant/templates/{id}")
    @ApiOperation("获取商家规格模板详情")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<ProductSpecTemplate> getMerchantSpecDetail(
            @PathVariable @NotNull(message = "规格ID不能为空") Long id) {
        try {
            // 获取当前商家ID
            Long userId = SecurityUtils.getCurrentUserId();
            Merchant merchant = merchantService.getOne(new LambdaQueryWrapper<Merchant>()
                    .eq(Merchant::getUserId, userId));
            if (merchant == null) {
                throw new BusinessException("未获取到商家信息");
            }

            // 获取规格模板
            ProductSpecTemplate template = specTemplateService.getById(id);
            if (template == null) {
                throw new BusinessException("规格模板不存在");
            }

            // 验证规格模板是否属于当前商家
            List<ProductSpecTemplate> merchantTemplates = specTemplateService.listByMerchantId(merchant.getId(), null);
            if (merchantTemplates.stream().noneMatch(t -> t.getId().equals(id))) {
                throw new BusinessException("无权访问该规格模板");
            }

            return ApiResponse.success(template);
        } catch (BusinessException e) {
            log.error("获取商家规格模板详情失败: error={}", e.getMessage());
            return ApiResponse.error(e);
        } catch (Exception e) {
            log.error("获取商家规格模板详情失败", e);
            return ApiResponse.error("获取商家规格模板详情失败");
        }
    }

    @GetMapping("/global/templates/{id}")
    @ApiOperation("获取全局规格模板详情")
    @PreAuthorize("hasAnyRole('MERCHANT','ADMIN')")
    public ApiResponse<GlobalSpecTemplate> getGlobalSpecDetail(
            @PathVariable @NotNull(message = "规格ID不能为空") Long id) {
        try {
            GlobalSpecTemplate template = globalSpecService.getById(id);
            if (template == null) {
                throw new BusinessException("规格模板不存在");
            }
            return ApiResponse.success(template);
        } catch (BusinessException e) {
            log.error("获取全局规格模板详情失败: error={}", e.getMessage());
            return ApiResponse.error(e);
        } catch (Exception e) {
            log.error("获取全局规格模板详情失败", e);
            return ApiResponse.error("获取全局规格模板详情失败");
        }
    }

  // ==================== 商家接口 ====================
    @PostMapping("/merchant/templates")
    @ApiOperation("创建规格")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<Long> create(@RequestBody @Validated ProductSpecDTO specDTO) {
        // 获取当前商家ID
        Long userId = SecurityUtils.getCurrentUserId();
        Merchant merchant = merchantService.getOne(new LambdaQueryWrapper<Merchant>()
                .eq(Merchant::getUserId, userId));
        if (merchant == null) {
            throw new BusinessException("未获取到商家信息");
        }
        specDTO.setMerchantId(merchant.getId());
        return ApiResponse.success(specTemplateService.saveSpecTemplate(specDTO));
    }

    @PutMapping("/merchant/templates/{id}")
    @ApiOperation("更新规格")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<Void> update(
            @PathVariable @NotNull(message = "规格ID不能为空") Long id,
            @RequestBody @Validated ProductSpecDTO specDTO) {
        specDTO.setId(id);
        specTemplateService.updateSpecTemplate(specDTO);
        return ApiResponse.success();
    }

    @DeleteMapping("/merchant/templates/{id}")
    @ApiOperation("删除规格")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<Void> delete(@PathVariable @NotNull(message = "规格ID不能为空") Long id) {
        specTemplateService.deleteSpecTemplate(id);
        return ApiResponse.success();
    }

    // ==================== 管理员接口 ====================
    @PostMapping("/global")
    @ApiOperation("创建全局规格模板")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Boolean> createGlobalSpec(@RequestBody @Validated GlobalSpecTemplate template) {
        return ApiResponse.success(globalSpecService.createGlobalSpec(template));
    }

    @PutMapping("/global/{id}")
    @ApiOperation("更新全局规格模板")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Boolean> updateGlobalSpec(
            @PathVariable Long id,
            @RequestBody @Validated GlobalSpecTemplate template) {
        template.setId(id);
        return ApiResponse.success(globalSpecService.updateGlobalSpec(template));
    }

    @PutMapping("/global/{id}/status")
    @ApiOperation("更新全局规格模板状态")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Boolean> updateGlobalSpecStatus(
            @PathVariable Long id,
            @RequestParam Boolean enabled) {
        return ApiResponse.success(globalSpecService.updateStatus(id, enabled));
    }

    @DeleteMapping("/global/{id}")
    @ApiOperation("删除全局规格模板")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Boolean> deleteGlobalSpec(
            @PathVariable @NotNull(message = "规格模板ID不能为空") Long id) {
        return ApiResponse.success(globalSpecService.deleteGlobalSpec(id));
    }

    @DeleteMapping("/global/batch")
    @ApiOperation("批量删除全局规格模板")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Boolean> batchDeleteGlobalSpecs(
            @RequestBody @NotEmpty(message = "规格模板ID列表不能为空") List<Long> ids) {
        return ApiResponse.success(globalSpecService.batchDeleteGlobalSpecs(ids));
    }

}